package com.hupu.jrs.ui.content

import android.content.Context
import android.text.TextUtils
import com.hupu.jrs.otto.UpdateContentPageEvent
import com.hupu.jrs.util.ShareUtil
import com.hupu.jrs.util.ToastUtil
import com.squareup.otto.Bus
import com.squareup.otto.Subscribe

import javax.inject.Inject

import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1

/**
 * Created by sll on 2016/3/9.
 */
class ContentPresenter @Inject
constructor(private val mForumApi: ForumApi, private val mContext: Context, private val mUserStorage: UserStorage, private val mBus: Bus) : ContentContract.Presenter {

    private var mContentView: ContentContract.View? = null
    private var mSubscription: Subscription? = null

    private var tid: String? = null
    private var fid: String? = null
    private var pid: String? = null
    private var totalPage = 1
    private var currentPage = 1
    private var isCollected: Boolean = false
    private var title: String? = null
    private var shareText: String? = null
    private var isSuccess: Boolean = false

    private val isLogin: Boolean
        get() {
            if (!mUserStorage.isLogin()) {
                mContentView!!.showLoginUi()
                return false
            }
            return true
        }

    override fun onThreadInfoReceive(tid: String, fid: String, pid: String, page: Int) {
        this.tid = tid
        this.fid = fid
        this.pid = pid
        mContentView!!.showLoading()
        loadContent(page)
    }

    private fun loadContent(page: Int) {
        mSubscription = mForumApi.getThreadSchemaInfo(tid, fid, page, pid)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Action1<Any> { threadSchemaInfo ->
                    if (threadSchemaInfo != null) {
                        if (threadSchemaInfo.error != null) {
                            mContentView!!.onError(threadSchemaInfo.error.text)
                        } else {
                            totalPage = threadSchemaInfo.pageSize
                            currentPage = threadSchemaInfo.page
                            shareText = threadSchemaInfo.share.weibo
                            title = threadSchemaInfo.share.wechat_moments
                            mContentView!!.renderContent(currentPage, totalPage)
                            isCollected = threadSchemaInfo.isCollected === 1
                            mContentView!!.isCollected(isCollected)
                            mContentView!!.hideLoading()
                            isSuccess = true
                        }
                    } else {
                        mContentView!!.onError("加载失败")
                    }
                }, Action1<Throwable> {
                    mContentView!!.renderContent(currentPage, totalPage)
                    mContentView!!.hideLoading()
                })
    }

    override fun onReload() {
        mContentView!!.showLoading()
        loadContent(currentPage)
    }

    override fun onRefresh() {
        loadContent(currentPage)
    }

    override fun onPageNext() {
        currentPage++
        if (currentPage >= totalPage) {
            currentPage = totalPage
        }
        mContentView!!.setCurrentItem(currentPage - 1)
    }

    override fun onPagePre() {
        currentPage--
        if (currentPage <= 1) {
            currentPage = 1
        }
        mContentView!!.setCurrentItem(currentPage - 1)
    }

    override fun onPageSelected(page: Int) {
        currentPage = page
        mContentView!!.setCurrentItem(currentPage - 1)
    }

    override fun onCommendClick() {
        if (isLogin) {
            mContentView!!.showPostUi(title)
        }
        mContentView!!.onToggleFloatingMenu()
    }

    override fun onShareClick() {
        if (!TextUtils.isEmpty(shareText)) {
            ShareUtil.share(mContext, shareText)
        }
        mContentView!!.onToggleFloatingMenu()
    }

    override fun onReportClick() {
        if (isLogin) {
            mContentView!!.showReportUi()
        }
        mContentView!!.onToggleFloatingMenu()
    }

    override fun onCollectClick() {
        if (isLogin) {
            if (isCollected) {
                delCollect()
            } else {
                addCollect()
            }
        }
        mContentView!!.onToggleFloatingMenu()
    }

    override fun updatePage(page: Int) {
        currentPage = page
        mContentView!!.onUpdatePager(currentPage, totalPage)
    }

    private fun addCollect() {
        mForumApi.addCollect(tid)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Action1<Any> { collectData ->
                    if (collectData != null && collectData.result != null) {
                        ToastUtil.showToast(collectData.result.msg)
                        isCollected = collectData.result.status === 200
                        mContentView!!.isCollected(isCollected)
                    }
                }, Action1<Throwable> { ToastUtil.showToast("收藏失败") })
    }

    private fun delCollect() {
        mForumApi.delCollect(tid)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Action1<Any> { collectData ->
                    if (collectData != null && collectData.result != null) {
                        ToastUtil.showToast(collectData.result.msg)
                        isCollected = collectData.result.status !== 200
                        mContentView!!.isCollected(isCollected)
                    }
                }, Action1<Throwable> { ToastUtil.showToast("取消收藏失败") })
    }

    fun attachView(view: ContentContract.View) {
        mContentView = view
        mBus.register(this)
    }

    fun detachView() {
        if (mSubscription != null && !mSubscription!!.isUnsubscribed) {
            mSubscription!!.unsubscribe()
        }
        mBus.unregister(this)
        mContentView = null
    }

    @Subscribe
    fun onUpdateContentPageEvent(event: UpdateContentPageEvent) {
        if (!isSuccess) {
            currentPage = event.getPage()
            totalPage = event.getTotalPage()
            mContentView!!.renderContent(currentPage, totalPage)
            isSuccess = true
        }
    }
}
